package de.luisoft.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;

import de.luisoft.dto.WahlDTO;

public class MyDAO {
	private static final Logger log = Logger.getLogger(MyDAO.class.getName());
	public Entity get(String key) throws EntityNotFoundException {
		DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

		Entity e = datastore.get(KeyFactory.createKey("wahl", key));
		return e;
	}
	public Entity verify(Entity e)throws EntityNotFoundException {
		
		log.info("verify " + e);
		DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

		e.setProperty("verified", Boolean.TRUE);
		Key k = datastore.put(e);
		return get(k.getName());
	}
	public Entity disable(Entity e)throws EntityNotFoundException {
		
		log.info("disable " + e);
		DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

		e.setProperty("disabled", Boolean.TRUE);
		Key k = datastore.put(e);
		return get(k.getName());
	}

	public long saveEntry(WahlDTO w) {
		log.info("saveEntry " + w);

		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Date date = new Date();
		Entity e = new Entity("wahl", String.valueOf(date.getTime()));

		e.setProperty("name", w.getName());
		e.setProperty("vorname", w.getVorname());
		e.setProperty("date", date);
		e.setProperty("email", w.getEmail());
		e.setProperty("klasse", w.getKlasse());
		e.setProperty("verified", Boolean.FALSE);
		e.setProperty("select", w.getSelect());

		log.info("saveEntry emp=" + e);
		Key k = datastore.put(e);
		log.info("saveEntry key=" + k);

		// return the key
		return date.getTime();
	}

	public String list() {
		log.info("list()");

		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Query q = new Query("wahl");
		// q.addFilter("lastName", Query.FilterOperator.EQUAL, lastNameParam);
		// q.addFilter("height", Query.FilterOperator.LESS_THAN,
		// maxHeightParam);
		//q.addSort("verified", SortDirection.ASCENDING);
		q.addSort("date", SortDirection.ASCENDING);

		// PreparedQuery contains the methods for fetching query results
		// from the datastore
		PreparedQuery pq = datastore.prepare(q);

		StringBuffer s = new StringBuffer("Datum;Name;Vorname;Klasse;Email;Verifiziert;Projektauswahl\n");

		int i = 0;
		for (Entity result : pq.asIterable()) {
			i++;
			String firstName = (String) result.getProperty("vorname");
			String lastName = (String) result.getProperty("name");
			// Long height = (Long) result.getProperty("height");
			s.append(result.getProperty("date") + ";"
					+ lastName + ";"
					+ firstName + ";"
					+ result.getProperty("klasse") + ";"
					+ result.getProperty("email") + ";"
					+ result.getProperty("verified") + ";"
					+ result.getProperty("select")
					+ result.getProperty("disabled")
					+ ";id="
					+ result.getKey().getName()
					+ "\n");
		}

		return s.toString() + "#=" + i;
	}

	public List<WahlDTO> getAllVerified(boolean verified) {
		log.info("getAllVerified()");

		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Query q = new Query("wahl");
		if (verified) {
			q.addFilter("verified", Query.FilterOperator.EQUAL, verified);
		}
		q.addSort("date", SortDirection.ASCENDING);

		PreparedQuery pq = datastore.prepare(q);

		Set<WahlDTO> l = new LinkedHashSet<WahlDTO>();
		for (Entity result : pq.asIterable()) {
			WahlDTO w = new WahlDTO();
			
			if (Boolean.TRUE.equals(result.getProperty("disabled"))) continue;

			String vorname = (String) result.getProperty("vorname");
			w.setVorname(vorname != null ? vorname.trim() : null);
			String name =(String) result.getProperty("name"); 
			w.setName(name != null ? name.trim() : null);
			String klasse = (String) result.getProperty("klasse"); 
			w.setKlasse(klasse != null ? klasse.trim() : null);
			String email = (String) result.getProperty("email");
			w.setEmail(email != null ? email.trim() : null);
			l.remove(w);
			List<String> sl = (List<String>) result.getProperty("select");
			if (sl == null) {
				w.setSelect(new ArrayList<String>());
				// skip entry
			} else {
				if (("freddy1199@t-online.de".equalsIgnoreCase(email) && "Frederik".equalsIgnoreCase(vorname))
						|| ("ulrike.glinka@arcor.de".equalsIgnoreCase(email) && "adrian".equalsIgnoreCase(vorname))
						|| ("tt.teigeler@t-online.de".equalsIgnoreCase(email) && "Juri".equalsIgnoreCase(vorname))
				) {
					sl.remove("Mountainbiking");
				}
				
				w.setSelect(sl);
				l.add(w);
			}
		}
		return new ArrayList<WahlDTO>(l);
	}

	public void delete() {
		log.info("delete()");
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Query q = new Query("wahl");
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			datastore.delete(result.getKey());
		}
	}

	public int deleteExpiredSessions() {
		log.info("deleteExpiredSessions()");
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Query q = new Query("_ah_SESSION");
		q.addFilter("_expires", Query.FilterOperator.LESS_THAN, System.currentTimeMillis());
		q.addSort("_expires", SortDirection.ASCENDING);
		PreparedQuery pq = datastore.prepare(q);
		int i = 0;
		for (Entity result : pq.asIterable()) {
//			datastore.delete(result.getKey());
			long exp = (Long) result.getProperty("_expires");
			System.out.println("deleting session entry " + new Date(exp));
			datastore.delete(result.getKey());
			i++;
		}

		q = new Query("_vac");
		q.addFilter("expires", Query.FilterOperator.LESS_THAN, System.currentTimeMillis());
		q.addSort("expires", SortDirection.ASCENDING);
		pq = datastore.prepare(q);

		for (Entity result : pq.asIterable()) {
//			datastore.delete(result.getKey());
			long exp = (Long) result.getProperty("expires");
			System.out.println("deleting vac entry " + new Date(exp));
			datastore.delete(result.getKey());
			i++;
		}
		
		return i;
	}
}
